<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :accept="props.accept"
      :action="uploadUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :on-change="handleChange"
      :headers="header"
      :multiple="limit == 1 ? false : true"
      v-if="limit != props.imageUrl.length"
    >
      <el-button v-if="props.upload_btn">上传</el-button>
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <div v-if="!props.upload_btn">
      <p class="c_999">建议尺寸：（{{ props.width }}x{{ props.height }}）*n</p>
      <div class="flex_wp m_top10">
        <div
          v-for="(item, index) in props.imageUrl"
          class="p_rel flex_cc m_bottom10 m_right10"
        >
          <el-tooltip :content="props.fileNames[index]" placement="bottom">
            <div
              v-if="props.uploadUrl != ''"
              @click="download(item)"
              @mouseenter="down_index = index"
              @mouseleave="down_index = Number"
              :style="{
                width: props.width + 'px',
                height: props.height + 'px',
              }"
            >
              <div
                v-show="down_index == index && downloadUrl != ''"
                class="down_icon flex_cc"
              >
                <el-icon :size="30" color="#777"><Download /></el-icon>
              </div>
              <img
                src="@/assets/img/file_default.png"
                :style="{
                  width: props.width + 'px',
                  height: props.height + 'px',
                }"
              />
            </div>
            <div v-else>
              <div
                class="cp"
                @click="
                  download_normal({
                    url: item,
                    fileName: props.fileNames[index],
                  })
                "
                v-if="!img_list.includes((item as any).split('.').at(-1))"
                :href=" (item as any)"
                @mouseenter="down_index = index"
                @mouseleave="down_index = Number"
                :style="{
                  width: props.width + 'px',
                  height: props.height + 'px',
                }"
              >
                <div v-show="down_index == index" class="down_icon flex_cc">
                  <el-icon :size="30" color="#777"><Download /></el-icon>
                </div>
                <img
                  src="@/assets/img/file_default.png"
                  :style="{
                    width: props.width + 'px',
                    height: props.height + 'px',
                  }"
                />
              </div>
              <el-image
                v-else
                :style="{
                  width: props.width + 'px',
                  height: props.height + 'px',
                }"
                :src="item"
                :preview-src-list="[item]"
                fit="scale-down"
                class="border"
                append-to-body
              ></el-image>
            </div>
          </el-tooltip>
          <!-- <el-icon :size="20" class="delete_icon" @click="delete_item(index)"
          ><delete-filled
        /></el-icon> -->
          <div class="delete_icon">
            <img
              @mouseenter="delete_index = index"
              v-if="delete_index != index"
              src="@/assets/img/tabs_close_1.png"
              style="width: 16px; height: 16px; border-radius: 50%"
              alt=""
            />
            <img
              v-if="delete_index == index"
              @click="delete_item(index)"
              @mouseleave="delete_index = -1"
              src="@/assets/img/tabs_close_2.png"
              style="width: 16px; height: 16px; border-radius: 50%"
              alt=""
            />
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-image-viewer
    v-if="preview_img_url != ''"
    :url-list="[preview_img_url]"
    fit="scale-down"
    class="border"
    append-to-body
    @close="preview_img_url = ''"
  ></el-image-viewer>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { getBaseURL } from "@/service/BaseURL";
import serviceApi from "@/service/api";
import { getCookie } from "@/utils/cookie";
import EventBus from "@/utils/EventBus";
import axios from "@/service/HttpRequest";
const img_list = ["png", "jpg", "jpeg", "gif", "svg", "psd", "fpx", "ai", "apng"];
const preview_img_url = ref("");
const down_index = ref();
const delete_index = ref(-1);
const handleChange = (file, fileLists) => {
  if (file.status == "success" && props.fileNames.length < props.imageUrl.length) {
    props.fileNames.push(file.name);
  }
  EventBus.emit("upload_succ");
};
const uploadUrl = computed(() => {
  // 上传 地址  判断是否有特殊地址
  return props.uploadUrl != ""
    ? getBaseURL() + props.uploadUrl
    : getBaseURL() + serviceApi.upload;
});
const header = {
  Authorization: getCookie("token"),
  EnterpriseId: getCookie("enterprise_id"),
};
const props = defineProps({
  limit: {
    // 上传数量
    type: Number,
    default: 1,
  },
  imageUrl: {
    // 上传图集
    type: Array,
    default: [],
  },
  width: {
    // 图集建议宽度
    type: Number,
    default: 48,
  },
  height: {
    // 图集建议高度
    type: Number,
    default: 48,
  },
  accept: {
    // 上传文件类型
    type: String,
    default: "",
  },
  uploadUrl: {
    // 特殊上传地址
    type: String,
    default: "",
  },
  downloadUrl: {
    // 特殊上传地址
    type: String,
    default: "",
  },
  fileNames: {
    type: Array,
    default: [],
  },
  minSize: {
    type: Number,
    default: 0,
  },
  maxSize: {
    type: Number,
    default: 0,
  },
  upload_btn: {
    type: Boolean,
    default: false,
  },
});
const handleAvatarSuccess = (res) => {
  console.log(res);
  if (res.code == 200) {
    if (props.imageUrl.length == props.limit) {
      ElMessage.error("最多上传 " + props.limit + " 个文件");
      return false;
    }
    // 特殊上传地址 --> 大样图管理  工程版本 不需要 全域名
    props.imageUrl.push(res.data.url);
  } else {
    ElMessage.error(res.data.message);
  }
};
const download_normal = (e) => {
  console.log(e);
  let http = new XMLHttpRequest();
  http.open("GET", e.url, true);
  http.responseType = "blob";
  http.onload = function () {
    const url = window.URL.createObjectURL(http.response);
    const a = document.createElement("a");
    a.href = url;
    a.download = e.fileName;
    a.click();
  };
  http.send();
};
const download = (e) => {
  if (props.downloadUrl == "") return;
  axios
    .request({
      url: props.downloadUrl + "/" + e,
      method: "get",
      responseType: "blob",
    })
    .then((res1) => {
      console.log(res1);
      const blob = new Blob([res1 as any]); // res.data 为接口返回的数据，依实例而行
      if (img_list.includes(e.split(".")[1])) {
        preview_img_url.value = window.URL.createObjectURL(blob); // 生成一个 Blob URL
      } else {
        const URL = window.URL.createObjectURL(blob); // 生成一个 Blob URL
        const fileName = props.fileNames[down_index.value]; // 文件名+后缀
        const listNode = document.createElement("a");
        listNode.download = fileName as any;
        listNode.style.display = "none";
        listNode.href = URL; // 文件流生成的url
        document.body.appendChild(listNode);
        listNode.click(); // 模拟在按钮上实现一次鼠标点击
        window.URL.revokeObjectURL(listNode.href); // 释放 URL 对象
        document.body.removeChild(listNode); // 移除 a 标签
      }
    });
};
const delete_item = (e) => {
  console.log(e);
  EventBus.emit("upload_succ");
  props.imageUrl.splice(e, 1);
  props.fileNames.splice(e, 1);
  delete_index.value = -1;
  console.log(props.imageUrl, props.fileNames);
};
const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile.name.split(".").at(-1).toLowerCase(), props.accept);
  if (
    ((props.maxSize ?? "") != "" &&
      Math.floor(rawFile.size / 1024 / 1024) > props.maxSize) ||
    ((props.minSize ?? "") != "" &&
      Math.floor(rawFile.size / 1024 / 1024) < props.minSize)
  ) {
    ElMessage.error("文件大小不符合配置条件");
    return false;
  }

  if (
    // 大样图 文件类型判断
    props.accept == "dwg" &&
    rawFile.name.split(".").at(-1).toLowerCase() != "dwg"
  ) {
    ElMessage.error("请上传dwg格式文件");
    return false;
  } else if (
    props.accept != "dwg" &&
    !props.accept.includes(rawFile.name.split(".").at(-1).toLowerCase())
  ) {
    ElMessage.error("请上传指定格式文件");
    return false;
  }
  //   if (rawFile.size / 1024 / 1024 > 5) {
  //     ElMessage.error('图片大小不得超过 5M!')
  //     return false
  //   }
  //   return true
};
</script>

<style scoped>
.delete_icon {
  cursor: pointer;
  position: absolute;
  right: 4px;
  top: 4px;
  z-index: 101;
}
.avatar-uploader .avatar {
  width: 48px;
  height: 48px;
  display: block;
}
.down_icon {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  background: rgba(0, 0, 0, 0.1);
}
.border {
  border: 1px solid #ccc;
}
.avatar-uploader .avatar {
  width: 48px;
  height: 48px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 48px;
  height: 48px;
  text-align: center;
}
</style>
